package derbyclnt.sockets;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageLite;
import static derbyclnt.Logger.*;

import derbyclnt.messages.*;

public final class RawData implements java.lang.Comparable<RawData>{
	final static int META_BYTE_SIZE = 7;
	private MetaProtos.Meta _meta;
	private byte[] _serializedMeta;
	private byte[] _data;


	private RawData() {
		clear();
	}
	
	public RawData(final MessageLite message, MessageTypesProtos.MessageTypes type) {
		this();
		_data = message.toByteArray();
		
		MetaProtos.Meta.Builder metaBuilder = MetaProtos.Meta.newBuilder();
		metaBuilder.setSize(_data.length);
		metaBuilder.setType(type); 
		
		assert(metaBuilder.isInitialized());
		_meta = metaBuilder.build();
		serializeMeta();
	}
	
	public RawData(byte[] meta) throws InvalidProtocolBufferException {
		assert meta != null;
		assert(meta.length == META_BYTE_SIZE);
		
		_serializedMeta = meta;
		deserializeMeta();
	}
	
	public int getSize() {
		return _meta.getSize();
	}
	public MessageTypesProtos.MessageTypes getType() {
		return _meta.getType();
	}
	public void setData(byte[] data) {
		assert data != null;
		assert data.length == getSize();
		if (data == null || data.length != getSize())
			throw new IllegalArgumentException("data");
		_data = data;
	}
	public byte[] getData() {
		assert _data != null;
		assert _data.length == getSize();
		return _data;
	}
	public byte[] getMetaData()  {
		assert _meta != null;
		assert _serializedMeta != null;
		return _serializedMeta;
	}
	
	private void serializeMeta() {
		assert(_meta != null);
		assert(_meta.isInitialized());
		logd("meta.getSerializedSize() = " + _meta.getSerializedSize());
		assert(_meta.getSerializedSize() == META_BYTE_SIZE);
		_serializedMeta = _meta.toByteArray();
		assert(_serializedMeta.length == META_BYTE_SIZE);
	}
	
	private void deserializeMeta() throws InvalidProtocolBufferException {
		assert(_serializedMeta != null);
		assert(_serializedMeta.length == META_BYTE_SIZE);
		_meta = MetaProtos.Meta.parseFrom(_serializedMeta);
	}
	
	private void clear() {
		_meta = null;
		_data = null;
		_serializedMeta = null;
	}

	@Override
	public int compareTo(RawData o) {
		// TODO Auto-generated method stub
		return 0;
	}
	
}
